<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { buildImage } from "@/api/api";
const route = useRoute();
const router = useRouter();
let socket = null;
const width = ref(0);
const timer = ref(null);
const errorMessage = ref("");

// 时间间隔 总时长 = 100 / 2 * timeNum
const timeNum = ref(400);
timer.value = setInterval(() => {
  if (width.value >= 100) {
    clearInterval(timer.value);
    width.value += 1; // 最后一次增加1%，防止进度条白边

    router.push("/small/share");
    return;
  }
  width.value += 2; // 每次增加2%
}, timeNum.value);

onMounted(() => {
  startSocket();
  generateImage();
});

const startSocket = () => {
  socket = io("http://b1740j1440.yicp.fun:47231/");

  socket.on("connect", function () {
    console.log("WebSocket 已连接");
    // 注册为小屏客户端
    socket.emit("register_client", { client_type: "small_screen" });
    socket.emit("confirm_location", {
      location_name: localStorage.getItem("location"),
      task_id: "pending_" + Date.now(),
    });
  });
};

// 生成图片
const generateImage = () => {
  // 清空resultObject
  localStorage.removeItem("resultObject");
  buildImage({
    gender: localStorage.getItem("modeType"),
    face: localStorage.getItem("croppedimage") || "",
    location: localStorage.getItem("location"),
  })
    .then((res) => {
      console.log(res, "res");
      let { success, error, data = {} } = res.data;
      if (success) {
        // 3. /build 接口生成成功后通知大屏幕显示生成结果
        socket.emit("generation_success", {
          location_name: localStorage.getItem("location"),
          result_data: data,
        });
        localStorage.setItem("resultObject", JSON.stringify(res.data));
      } else {
        errorMessage.value = error;
        // 4. /build 接口生成失败后通知大屏幕返回待机画面
        socket.emit("show_standby_page", {});

        setTimeout(() => {
          router.back();
        }, 3000);
      }
    })
    .catch((err) => {
      // 网络错误也通知大屏返回待机画面
      socket.emit("show_standby_page", {});
      errorMessage.value = err.error;
    });
};

onUnmounted(() => {
  clearInterval(timer.value);
});
</script>

<template>
  <div class="small">
    <Dialog v-if="errorMessage" :message="errorMessage"></Dialog>
    <div class="title">Now generating…</div>
    <div class="progress">
      <div class="progress-bar" :style="{ width: width + '%' }"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.title {
  width: 100%;
  position: absolute;
  top: 40%;
  font-size: 60px;
  font-family: "stc-medium";
  color: #fff;
  text-align: center;
  line-height: 1;
}
.progress {
  width: 660px;
  height: 40px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 0);
  background: #fff;
  font-size: 0px;
}
.progress-bar {
  width: 0%;
  height: 100%;
  display: inline-block;
  position: absolute;
  top: 0;
  left: -2px;
  background: #ff375e;
  transition: all 1s linear;
}
</style>
